﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Abc.Core.Entities;
using Abc.Utils;
using Furion;

using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace Abc.DataBase.Core
{
    [AppStartup(800)]
    public sealed class DatabaseCoreStartup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {

            var dboptions = AppEx.GetConfig<SqlSugarDbSettingOptions>();
            if (dboptions != null)
            {
                if (dboptions.EnableYitterIdGenerator)
                {
                    //5.1.3.53 起可用，自定义雪花ID使用
                    SqlSugar.StaticConfig.CustomSnowFlakeFunc = () => Yitter.IdGenerator.YitIdHelper.NextId();
                }

                if (dboptions.EnableInitDataSeed)
                {
                    //此设置需要在  services.AddSqlsugarSetup 之前注册
                    // 初始化数据种子委托方法扩展，执行完数据种子方法后调用，处理一些特殊扩展
                    SqlSugarHelper.InitDataSeedExFunc = (ISqlSugarClient _db) =>
                    {


                        return true;
                    };
                }
            }

            //如果使用 SqlSugar 需要注册此服务
            services.AddSqlsugarSetup(App.Configuration);


            //如使用非 EFCore ORM 框架，可实现 IUnitOfWork 接口之后调用 services.AddUnitOfWork<TUnitOfWork>() 注册即可
            services.AddUnitOfWork<SqlSugarUnitOfWork>();

            #region 配置查询
            //https://www.donet5.com/Home/Doc?typeId=2309
            var types = SqlSugarHelper.Db.Queryable<SysDataConfig>().Select(it => it.GroupName).Distinct().ToList();
            //上面有耗时操作写在Any上面，保证程序启动后只执行一次
            if (!SqlSugarHelper.Db.ConfigQuery.Any())
            {
                //数据字典配置
                foreach (var type in types)
                {
                    SqlSugarHelper.Db.ConfigQuery.SetTable<SysDataConfig>(it => it.Key, it => it.Name, type, it => it.GroupName == type);
                }

                //联表配置
                //db.ConfigQuery.SetTable<Order>(it => it.Id, it => it.Name);

            }

            #endregion
        }
    }
}